package com.wxy.netty.黏包半包处理;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Scanner;

public class Client3 {

    public static String getMessage() {
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine() + "\n";
    }

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ByteBuf buf = ctx.alloc().buffer();
                                int count = 0; // 计数：控制每次最多发送3条消息

                                while (true) {
                                    String message = getMessage();

                                    // 1. 检查是否输入exit（注意包含换行符）
                                    if ("exit\n".equals(message)) {
                                        ctx.writeAndFlush(buf);
                                        ctx.close(); // 立即关闭连接
                                        break;
                                    }

                                    // 2. 写入消息到缓冲区
                                    buf.writeBytes(message.getBytes());
                                    count++;

                                    // 3. 每累积3条消息就发送一次
                                    if (count >= 3) {
                                        ctx.writeAndFlush(buf);
                                        buf = ctx.alloc().buffer(); // 重置缓冲区
                                        count = 0; // 重置计数
                                    }
                                }
                            }
                        });
                    }
                }).connect("127.0.0.1", 8888).sync().channel();

        // 等待连接关闭后释放资源
        channel.closeFuture().addListener(future -> eventLoopGroup.shutdownGracefully());
    }
}